<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片区域-->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="userInfo.query" @clear="getUsersList" clearable>
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!--表格区域-->
    <el-table :data="userList" style="width: 100%" stripe border>
      <el-table-column type="index"></el-table-column>
      <el-table-column prop="username" label="姓名" width="180"></el-table-column>
      <el-table-column prop="mobile" label="手机号" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mg_state" label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" @click="editDiaLog(scope.row.id)"></el-button>
          <el-button type="danger" icon="el-icon-delete" @click="removeUserById(scope.row.id)"></el-button>
          <el-tooltip class="item" effect="dark" content="分配角色" placement="top-start" :enterable="false">
            <el-button type="warning"><i class="el-icon-upload el-icon--right"></i></el-button>
          </el-tooltip>
        
        </template>
      </el-table-column>
    </el-table>
    <!--分页区域-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="userInfo.pagenum"
      :page-sizes="[1, 2, 5, 7]"
      :page-size="userInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!--添加用户区域-->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="30%" @close="addFormClosed">
      <el-form :model="addUserForm" :rules="addUserRules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
    </el-dialog>
    
    <!--修改用户区域-->
    <el-dialog
      title="提示"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editFormClosed"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled=""></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserInfo">确 定</el-button>
  </span>
    </el-dialog>
  
  </div>

</template>

<script>
  
  export default {
    name: "Users",
    data() {
      //验证邮箱的规则
      const checkEmail = (rule, value, cb) => {
        const regEmail = /^\w+@\w+(\.\w+)+$/
        if (regEmail.test(value)) {
          return cb()
        }
        //返回一个错误提示
        cb(new Error('请输入合法的邮箱'))
      }
      //验证手机号码的规则
      const checkMobile = (rule, value, cb) => {
        const regMobile = /^1[34578]\d{9}$/
        if (regMobile.test(value)) {
          return cb()
        }
        //返回一个错误提示
        cb(new Error('请输入合法的手机号码'))
      }
      return {
        
        userInfo: {
          query: '',
          pagenum: 1,
          pagesize: 2
        },
        userList: [],
        total: 0,
        dialogVisible: false,
        editDialogVisible: false,
        //添加用户表单
        addUserForm: {
          username: '',
          password: '',
          mobile: '',
          email: ''
        },
        
        //添加用户表单验证规则
        addUserRules: {
          username: [
            {required: true, message: '请输入用户名称', trigger: 'blur'},
            {min: 3, max: 5, message: '长度在 3 到 10 个字符', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'}
          ],
          email: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {validator: checkEmail, message: '邮箱格式不正确，请重新输入', trigger: 'blur'}
          ],
          mobile: [
            {required: true, message: '请输入手机号码', trigger: 'blur'},
            {validator: checkMobile, message: '手机号码不正确，请重新输入', trigger: 'blur'}
          ]
        },
        //添加修改用户信息
        editForm: {},
        editFormRules: {
          email: [
            {required: true, message: '请输入邮箱', trigger: 'blur'},
            {validator: checkEmail, message: '邮箱格式不正确，请重新输入', trigger: 'blur'}
          ],
          mobile: [
            {required: true, message: '请输入手机号码', trigger: 'blur'},
            {validator: checkMobile, message: '手机号码不正确，请重新输入', trigger: 'blur'}
          ]
        }
      }
    },
    created() {
      this.getUsersList()
    },
    methods: {
      async getUsersList() {
        const {data: res} = await this.$http.get('users', {params: this.userInfo})
        // console.log(res)
        // console.log(res.data.users)
        if (res.data.status === 200) {
          return this.$message.error('获取用户列表失败')
        }
        this.userList = res.data.users
        // console.log(this.userList)
        this.total = res.data.total
      },
      //监听页面大小变化
      handleSizeChange(newSize) {
        this.userInfo.pagesize = newSize
        this.getUsersList()
      },
      handleCurrentChange(newPage) {
        this.userInfo.pagenum = newPage
        this.getUsersList()
      },
      //改变用户状态
      async changeUserState(userInfo) {
        console.log(userInfo)
        const res = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
        // console.log(res)
        if (res.meta.status !== 200) {
          userInfo.mg_state = !userInfo.mg_state
          return this.$message.error('修改用户状态失败')
        }
      },
      //对话框关闭前的清空表单
      addFormClosed() {
        this.$refs.ruleForm.resetFields()
      },
      //表单提交前的预校验
      addUser() {
        this.$refs.ruleForm.validate(async valid => {
          if (!valid) return
          //如果成功,那么发送请求
          const {data: res} = await this.$http.post('users', this.addUserForm)
          // console.log(res)
          if (res.meta.status !== 201) return this.$message.error('添加用户失败')
          this.$message.success('添加用户成功')
          this.dialogVisible = false
          this.getUsersList()
        })
      },
      //  修改用户信息
      async editDiaLog(id) {
        this.editDialogVisible = true
        console.log(id)
        const {data: res} = await this.$http.get('users/' + id)
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('查询用户信息失败')
        }
        this.editForm = res.data
        
      },
      //监听修改用户窗口关闭时间
      editFormClosed() {
        this.$refs.editFormRef.resetFields()
      },
      //修改用户数据并提交
      editUserInfo() {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return
          //若果验证通过,发送请求
          const {data: res} = await this.$http.put('users/' + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
          if (res.meta.status !== 200) {
            return this.$message.error('修改用户信息失败')
          }
          //如果成功,先关闭对话框
          this.editDialogVisible = false
          //  刷新用户列表数据
          this.getUsersList()
          //提示修改成功
          this.$message.success('修改用户信息成功')
        })
      },
      //删除用户操作
      async removeUserById(id) {
        const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // console.log(result)
        //如果点击确定,返回的是字符串的confirm
        //如果点击的是取消,返回的是字符串的cancel
        //所以可以通过这个来判断
        if (result !== 'confirm') {
          //此时说明用户不想删除
          this.$message.info('已经取消删除了')
        }
        const {data: res} = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) {
          return this.$message.error('删除用户失败')
        }
        this.$message.success('删除用户成功')
        this.getUsersList()
      }
    }
  }
</script>

<style scoped>

</style>
